package com.cn.kabalifeuser.ui.order.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cn.kabalifeuser.R;
import com.cn.kabalifeuser.base.IBaseActivity;
import com.cn.kabalifeuser.config.LoginHelper;
import com.cn.kabalifeuser.ui.order.bean.ServiceOrderDetailsBean;
import com.cn.kabalifeuser.ui.service.adapter.PisListAdapter;
import com.cn.kabalifeuser.utils.GlideEngine;
import com.cn.kabalifeuser.utils.GlideUtil;
import com.cn.kabalifeuser.utils.RxToast;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.ToastUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by 晓林 on 2020/9/27.
 * function: 服务订单。详情
 */
public class ServiceOrderDetailsActivity extends IBaseActivity<ServiceOrderView, ServiceOrderPresenter> implements ServiceOrderView {

    ServiceOrderDetailsBean serviceOrderDetailsBean;
    Bundle bundle;
    int id;
    @BindView(R.id.top_tv_status_bar)
    TextView topTvStatusBar;
    @BindView(R.id.img_user_head)
    CircleImageView imgUserHead;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_user_phone)
    TextView tvUserPhone;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_budget)
    TextView tvBudget;
    @BindView(R.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R.id.tv_created_at)
    TextView tvCreatedAt;
    @BindView(R.id.tv_true_money)
    TextView tvTrueMoney;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.rv_pics)
    RecyclerView rvPics;

    List<String> mListPics;
    PisListAdapter mAdapterPic;
    List<LocalMedia> selectList = new ArrayList<>();
    @BindView(R.id.tv_deposit)
    TextView tvDeposit;
    @BindView(R.id.tv_discount)
    TextView tvDiscount;
    @BindView(R.id.tv_balance)
    TextView tvBalance;
    @BindView(R.id.tv_true_discount)
    TextView tvTrueDiscount;
    @BindView(R.id.tv_bus_address)
    TextView tvBusAddress;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_tel)
    TextView tvTel;
    @BindView(R.id.tv_address)
    TextView tvAddress;

    @Override
    protected ServiceOrderPresenter createPresenter() {
        return new ServiceOrderPresenter();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_service_details;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        setTitleBar("订单详情");
        bundle = getIntent().getExtras();
        id = bundle.getInt("id");
        mListPics = new ArrayList<>();
        rvPics.setLayoutManager(new GridLayoutManager(this, 3));
        rvPics.setNestedScrollingEnabled(false);
        //创建适配器
        mAdapterPic = new PisListAdapter(R.layout.pics_list_pic_item, mListPics);
        //给RecyclerView设置适配器
        rvPics.setAdapter(mAdapterPic);

        mAdapterPic.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                PictureSelector.create(ServiceOrderDetailsActivity.this)
                        .themeStyle(R.style.picture_default_style) // xml设置主题
                        //.setPictureStyle(mPictureParameterStyle)// 动态自定义相册主题
                        //.setPictureWindowAnimationStyle(animationStyle)// 自定义页面启动动画
                        .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)// 设置相册Activity方向，不设置默认使用系统
                        .isNotPreviewDownload(true)// 预览图片长按是否可以下载
                        .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                        .openExternalPreview(position, selectList);
            }
        });
        mPresenter.onOrderDetailsData(LoginHelper.getLonginData().getResult(), id);


//        tvUserPhone.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG );
    }

    @Override
    public void onReLoggedIn(String msg) {
        RxToast.error(msg);
        LoginHelper.againGoToLoginActivity(getMe());
    }

    @Override
    public void onError(String msg) {
        RxToast.error(msg);
    }

    @Override
    public Context _getContext() {
        return getMe();
    }

    @Override
    public void onOrderDetailsSuccess(ServiceOrderDetailsBean bean) {
        serviceOrderDetailsBean =bean;
        GlideUtil.ImageLoad(this, bean.getResult().getHead(), imgUserHead);
        tvUserName.setText(bean.getResult().getNickname());
        tvUserPhone.setText(bean.getResult().getPhone());
        tvTitle.setText(bean.getResult().getTitle());
        tvBudget.setText("￥" + bean.getResult().getBudget());
        tvStartTime.setText(bean.getResult().getStart_time());
        tvCreatedAt.setText(bean.getResult().getCreated_at());
        tvTrueMoney.setText("￥" + bean.getResult().getTrue_money());
        tvContent.setText(bean.getResult().getContent());
        mAdapterPic.replaceData(bean.getResult().getImg());


        tvBusAddress.setText(bean.getResult().getBus_address());
        tvName.setText(bean.getResult().getName());
        tvTel.setText(bean.getResult().getTel());
        tvAddress.setText(bean.getResult().getAddress());


        tvDeposit.setText("￥" + bean.getResult().getDeposit());
        tvDiscount.setText("￥" + bean.getResult().getDiscount());
        tvBalance.setText("￥" + bean.getResult().getBalance());
        tvTrueDiscount.setText("￥" + bean.getResult().getTrue_discount());


        for (String str : bean.getResult().getImg()) {
            LocalMedia localMedia = new LocalMedia();
            localMedia.setPath(str);
            selectList.add(localMedia);
        }
    }



    @OnClick({R.id.tv_user_phone, R.id.tv_bus_address, R.id.tv_tel, R.id.tv_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_user_phone:
                if (serviceOrderDetailsBean!=null && !TextUtils.isEmpty(serviceOrderDetailsBean.getResult().getPhone())) {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + serviceOrderDetailsBean.getResult().getPhone());
                    intent.setData(data);
                    startActivity(intent);
                }
                break;
            case R.id.tv_bus_address:
                if (!TextUtils.isEmpty(serviceOrderDetailsBean.getResult().getAddress())) {
                    if (checkMapAppsIsExist(this, "com.baidu.BaiduMap")) {
                        openBaiduMap(0, 0, serviceOrderDetailsBean.getResult().getBus_address());
                    } else if (checkMapAppsIsExist(this, "com.autonavi.minimap")) {
                        openGaoDeMap(0, 0, serviceOrderDetailsBean.getResult().getBus_address());
                    }
                }
                break;
            case R.id.tv_tel:
                if (serviceOrderDetailsBean!=null && !TextUtils.isEmpty(serviceOrderDetailsBean.getResult().getTel())) {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + serviceOrderDetailsBean.getResult().getTel());
                    intent.setData(data);
                    startActivity(intent);
                }
                break;
            case R.id.tv_address:
                if (!TextUtils.isEmpty(serviceOrderDetailsBean.getResult().getAddress())) {
                    if (checkMapAppsIsExist(this, "com.baidu.BaiduMap")) {
                        openBaiduMap(0, 0, serviceOrderDetailsBean.getResult().getAddress());
                    } else if (checkMapAppsIsExist(this, "com.autonavi.minimap")) {
                        openGaoDeMap(0, 0, serviceOrderDetailsBean.getResult().getAddress());
                    }
                }
                break;
        }
    }

    /**
     * 打开高德地图（公交出行，起点位置使用地图当前位置）
     *
     * t = 0（驾车）= 1（公交）= 2（步行）= 3（骑行）= 4（火车）= 5（长途客车）
     *
     * @param dlat  终点纬度
     * @param dlon  终点经度
     * @param dname 终点名称
     */
    private void openGaoDeMap(double dlat, double dlon, String dname) {
        if (checkMapAppsIsExist(this, "com.autonavi.minimap")) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setPackage("com.autonavi.minimap");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.setData(Uri.parse("androidamap://route?sourceApplication=" + R.string.app_name
                    + "&sname=我的位置&dlat=" + dlat
                    + "&dlon=" + dlon
                    + "&dname=" + dname
                    + "&dev=0&m=0&t=1"));
            startActivity(intent);
        } else {
            RxToast.error("高德地图未安装");
        }
    }
    /* 打开百度地图（公交出行，起点位置使用地图当前位置）
     *
      * mode = transit（公交）、driving（驾车）、walking（步行）和riding（骑行）. 默认:driving
      * 当 mode=transit 时 ： sy = 0：推荐路线 、 2：少换乘 、 3：少步行 、 4：不坐地铁 、 5：时间短 、 6：地铁优先
      *
      * @param dlat  终点纬度
     * @param dlon  终点经度
     * @param dname 终点名称
     */
    private void openBaiduMap(double dlat, double dlon, String dname) {
        if (checkMapAppsIsExist(this, "com.baidu.BaiduMap")) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("baidumap://map/direction?origin=我的位置&destination=name:"
                    + dname
                    + "|latlng:" + dlat + "," + dlon
                    + "&mode=transit&sy=3&index=0&target=1"));
            startActivity(intent);
        } else {
            RxToast.error("百度地图未安装");
        }
    }
    /**
     * 打开腾讯地图（公交出行，起点位置使用地图当前位置）
     *
     * 公交：type=bus，policy有以下取值
     * 0：较快捷 、 1：少换乘 、 2：少步行 、 3：不坐地铁
     * 驾车：type=drive，policy有以下取值
     * 0：较快捷 、 1：无高速 、 2：距离短
     * policy的取值缺省为0
     *
     * @param dlat  终点纬度
     * @param dlon  终点经度
     * @param dname 终点名称
     */
    private void openTencent(double dlat, double dlon, String dname) {
        if (checkMapAppsIsExist(this, "com.tencent.map")) {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("qqmap://map/routeplan?type=bus&from=我的位置&fromcoord=0,0"
                    + "&to=" + dname
                    + "&tocoord=" + dlat + "," + dlon
                    + "&policy=1&referer=myapp"));
            startActivity(intent);
        } else {
            RxToast.error("腾讯地图未安装");
        }
    }
    public boolean checkMapAppsIsExist(Context context, String packagename) {
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(packagename, 0);
        } catch (Exception e) {
            packageInfo = null;
            e.printStackTrace();
        }
        return packageInfo != null;
    }
}
